const fs = require('node:fs/promises');
const path = require('path');

function p(relativePath) {
    return path.join(__dirname, relativePath);
}

;(async () => {
    await fs.mkdir(p('./a')).catch((err) => {
        console.log(err);
    });
    await Promise.all([
        fs.writeFile(p('./a/1.js'), 'const a = 1   ;    let b = 2; var c = 3;').catch(() => {}), // 8min
        fs.writeFile(p('./a/2.js'), 'const d = 1; const e = 1;').catch(() => {}), // 10min
    ]);
    const content1 = await fs.readFile(path.join(__dirname, p('./a/1.js')), { encoding: 'utf-8' }); // 1.js
    const content2 = await fs.readFile(p('./a/2.js'), { encoding: 'utf-8' });

    const KEYWORDS = [
        'const',
        'let',
        'var',
        // ...
    ];
    // [ 'const a = 1', ' let b = 2', ' var c = 3', '' ]
    const varNameList1 = content1
        .split(';')
        .map(c => {
            for (const keyword of KEYWORDS) {
                c = c.replace(keyword, '');
            }
            // c >>> ' a = 1'
            const [varName] = c.split('='); // ' a '
            return varName.trim();
        })
        .filter(c => c); // ['a', 'b', 'c']
    const varNameList2 = content2
        .split(';')
        .map(c => {
            for (const keyword of KEYWORDS) {
                c = c.replace(keyword, '');
            }
            const [varName] = c.split('='); // ' a '
            return varName.trim();
        })
        .filter(c => c); // ['d', 'e']

    // ['a', 'b', 'c', 'd', 'e'] >> ['console.log(a);', ...]
    // 10min之后
    const content = content1 + content2 + varNameList1.concat(varNameList2).map(v => `console.log(${v});`).join('');
    fs.writeFile(p('./a/3.js'), content.replace(/[ ]{0,}\;[ ]{0,}/g, ';\n'));
})();
